package com.example.myapplication3.image;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;

import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.myapplication3.R;
import com.example.myapplication3.base.BaseActivity;
import com.example.myapplication3.image.adapter.ImageAdapter;
import com.example.myapplication3.image.bean.ImageItem;
import com.example.myapplication3.video.adapter.VideoAdapter;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;


import java.util.ArrayList;
import java.util.List;

public class ImageActivity extends BaseActivity {

    private ImageAdapter adapter;
    private SmartRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private List<ImageItem> dataList;
    private int pageIndex;
    private int size = 24;

    @Override
    public int getLayoutMain() {
        return R.layout.activity_image;
    }

    @Override
    public void initData() {
        dataList = new ArrayList<>();
        adapter = new ImageAdapter(dataList,this);
    }

    @Override
    public void initView() {
        setSupportActionBar(findViewById(R.id.toolbar));
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        refreshLayout = findViewById(R.id.smartrefreshlayout);
        recyclerView = findViewById(R.id.recyclerview);
        setShowMode(ImageAdapter.MODE_LIST);
        registerForContextMenu(recyclerView);

        refreshLayout.autoRefresh();
    }
    @Override
    public void initListener() {
        refreshLayout.setOnRefreshListener( refreshLayout->{
            loadImageData();
        });
        refreshLayout.setOnLoadMoreListener(refreshLayout -> {
            loadImageData();
        });

    ImageQueryHelper.setImageLoadCallback(images -> {
        if (images==null){
            Toast.makeText(this,"没有数据",Toast.LENGTH_SHORT).show();
            refreshLayout.finishRefresh(false);
            refreshLayout.finishLoadMore(false);
            return;
        }
        dataList.addAll(images);
        runOnUiThread(() -> {
            adapter.notifyItemRangeChanged(pageIndex * size, size);
            refreshLayout.finishRefresh(true);
            refreshLayout.finishLoadMore(true);
        });
    });

    adapter.setItemOnClickListener((v, position) -> {
        ImageItem imageItem = dataList.get(position);
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(imageItem.getUri(), imageItem.getMimeType());
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);// 授予临时读取权限
        startActivity(intent);
    });
    adapter.setItemOnLongClickListener((View v, int position) -> {
            // 已由上下文菜单处理
        });
    }
    private void loadImageData() {
        // 检查权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_IMAGES)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{
                            Manifest.permission.READ_MEDIA_IMAGES
                    },
                    1);
            return;
        }
        ImageQueryHelper.asynLoadAllImages(this, pageIndex++, size);
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            loadImageData(); // 权限通过后重试
        }
    }
    private void setShowMode(int mode) {
        adapter.setMode(mode);
        switch (mode) {
            case ImageAdapter.MODE_GRID:
                GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false);
                recyclerView.setLayoutManager(gridLayoutManager);
                break;
            case ImageAdapter.MODE_LIST:
            default:
                LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
                recyclerView.setLayoutManager(linearLayoutManager);
                break;
        }
        recyclerView.setAdapter(adapter);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_imageview_show,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId()==android.R.id.home){
            finish();
        }
        if (item.getItemId()==R.id.menu_list){
            setShowMode(VideoAdapter.MODE_LIST);
            return true;
        }
        if (item.getItemId()==R.id.menu_grid){
            setShowMode(VideoAdapter.MODE_GRID);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        getMenuInflater().inflate(R.menu.menu_longcilck,menu);
        super.onCreateContextMenu(menu, v, menuInfo);
    }

    @Override
    public boolean onContextItemSelected(@NonNull MenuItem item) {
        if (item.getItemId()==R.id.menu_delete){
            Toast.makeText(this,"delete",Toast.LENGTH_SHORT).show();
        }
        if (item.getItemId()==R.id.menu_rename){
            Toast.makeText(this,"rename",Toast.LENGTH_SHORT).show();
        }
        return super.onContextItemSelected(item);
    }
}